package com.situ.mall.admin.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.situ.mall.admin.pojo.dto.AdminLoginDTO;
import com.situ.mall.admin.pojo.dto.AdminPasswordDTO;
import com.situ.mall.admin.pojo.query.AdminQuery;
import com.situ.mall.admin.service.IAdminService;
import com.situ.mall.common.constants.RedisConstants;
import com.situ.mall.common.util.CommonUtil;
import com.situ.mall.common.util.JwtUtil;
import com.situ.mall.common.util.MD5Util;
import com.situ.mall.common.util.Result;
import com.situ.mall.pojo.entity.admin.Admin;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Sun Huijuan
 * @since 2024-10-09
 */
@RestController
@RequestMapping("/admin")
public class AdminController {
	@Autowired
	private IAdminService adminService;
	
	@Autowired
	private RedisTemplate redisTemplate;
	
	//内网穿透示例
	@GetMapping("/")
	public String index() {
		return "success";
	}
	
	//后台分页&条件查询管理员列表
	@GetMapping("/list")
	public Result list(AdminQuery adminQuery) {
		IPage<Admin> page = new Page<>(adminQuery.getPage(), adminQuery.getLimit());
		QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
		queryWrapper.like(!ObjectUtils.isEmpty(adminQuery.getName()), "name", adminQuery.getName());
		queryWrapper.like(!ObjectUtils.isEmpty(adminQuery.getPhone()), "phone", adminQuery.getPhone());
		queryWrapper.between(!ObjectUtils.isEmpty(adminQuery.getBeginUpdateTime())&&!ObjectUtils.isEmpty(adminQuery.getEndUpdateTime()),
				"update_time",adminQuery.getBeginUpdateTime(),adminQuery.getEndUpdateTime());
		adminService.page(page, queryWrapper);
		Map<String, Object> map = new HashMap<>();
		map.put("total", page.getTotal());
		map.put("list", page.getRecords());
		return Result.ok(map);
	}
	
	//单个删除
	@DeleteMapping("/deleteById/{id}")
	public Result deleteById(@PathVariable Integer id) {
		adminService.removeById(id);
		return Result.ok("删除成功！");
	}
	
	//批量删除
	@DeleteMapping("/deleteAll/{ids}")
	public Result deleteAll(@PathVariable Integer[] ids) {
		adminService.removeByIds(Arrays.asList(ids));
		return Result.ok("删除成功！");
	}
	
	//添加管理员
	@PostMapping("/add")
	public Result add(@RequestBody Admin admin) {
		adminService.save(admin);
		redisTemplate.opsForSet().add(RedisConstants.UPLOAD_IMAGE_TO_DB, admin.getImage());
		return Result.ok("添加成功！");
	}
	
	//查询单个管理员信息
	@GetMapping("/selectById/{id}")
	public Result<Admin> selectById(@PathVariable Integer id) {
		Admin admin = adminService.getById(id);
		return Result.ok(admin);
	}
	
	//修改信息
	@PutMapping("/update")
	public Result update(@RequestBody Admin admin) {
		adminService.saveOrUpdate(admin);
		redisTemplate.opsForSet().add(RedisConstants.UPLOAD_IMAGE_TO_DB, admin.getImage());
		return Result.ok("修改成功！");
	}
	
	//管理员后台登录
	@PostMapping("/login")
	public Result login(@RequestBody AdminLoginDTO adminLoginDTO, HttpServletRequest request) {
		//判断验证码是否正确
		String captcha = (String) redisTemplate.opsForValue().get(CommonUtil.getCaptchaKey(request));
		//判断验证码是否有效
		if(StringUtils.isEmpty(captcha)){
			return Result.error("验证码已失效");
		}
		if(!captcha.equalsIgnoreCase(adminLoginDTO.getCaptcha())){
			return Result.error("验证码错误！");
		}
		QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("name", adminLoginDTO.getName());
		//根据用户名查询用户
		Admin loginAdmin = adminService.getOne(queryWrapper);
		//用户名不存在
		if (loginAdmin == null) {
			return Result.error("用户名不存在！");
		}
		//判断密码是否正确
		if (!MD5Util.MD5Encode(adminLoginDTO.getPassword()).equals(loginAdmin.getPassword())) {
			return Result.error("密码错误！");
		}
		//判断管理员的账号状态
		if(loginAdmin.getStatus()==0){
			return Result.error("该用户被禁用");
		}
		//登录成功
		//构建Token
		Map<String,Object> map=new HashMap<>();
		map.put("id",loginAdmin.getId());
		map.put("name",loginAdmin.getName());
		String token = JwtUtil.createToken(map);
		return Result.ok("登录成功", token);
	}
	
	//获取登录管理员的个人信息
	@GetMapping("/adminInfo")
	public Result adminInfo(@RequestHeader(name = "Authorization")String token) {
		String name = (String) JwtUtil.parseToken(token).get("name");
		QueryWrapper queryWrapper = new QueryWrapper();
		queryWrapper.eq("name", name);
		Admin admin = adminService.getOne(queryWrapper);
		return Result.ok(admin);
	}
	
	//修改管理员账号状态
	@PutMapping("/updateStatus/{id}/{status}")
	public Result updateStatus(@PathVariable Integer id, @PathVariable Integer status){
		UpdateWrapper<Admin> updateWrapper=new UpdateWrapper<>();
		updateWrapper.eq("id",id).set("status",status);
		adminService.update(updateWrapper);
		return Result.ok("修改成功！");
	}
	
	//修改管理员角色类型
	@PutMapping("/updateRole/{id}/{role}")
	public Result updateRole(@PathVariable Integer id, @PathVariable Integer role){
		UpdateWrapper<Admin> updateWrapper=new UpdateWrapper<>();
		updateWrapper.eq("id",id).set("role",role);
		adminService.update(updateWrapper);
		return Result.ok("修改成功！");
	}
	
	//超级管理员重置管理员密码为默认密码【123456】，MD5加密后传入后台
	@PutMapping("/defaultPassword/{id}")
	public Result defaultPassword(@PathVariable Integer id){
		String password=MD5Util.MD5Encode("123456");
		UpdateWrapper<Admin> updateWrapper=new UpdateWrapper<>();
		updateWrapper.eq("id",id).set("password",password);
		adminService.update(updateWrapper);
		return Result.ok("重置默认密码成功！！");
	}
	
	//管理员重置个人密码
	@PutMapping("/resetPassword")
	public Result resetPassword(@RequestBody AdminPasswordDTO adminPasswordDTO,
								@RequestHeader(name = "Authorization")String token){
		Map<String,Object> map=JwtUtil.parseToken(token);
		Integer id=(Integer)map.get("id");
		QueryWrapper queryWrapper = new QueryWrapper();
		queryWrapper.eq("id", id);
		queryWrapper.eq("password",MD5Util.MD5Encode(adminPasswordDTO.getOldPassword()));
		Admin admin = adminService.getOne(queryWrapper);
		if(admin==null){
			return Result.error("原密码错误！");
		}
		UpdateWrapper<Admin> updateWrapper=new UpdateWrapper<>();
		String password=MD5Util.MD5Encode(adminPasswordDTO.getNewPassword());
		updateWrapper.eq("id",id).set("password",password);
		adminService.update(updateWrapper);
		return Result.ok("修改成功！");
	}
}

